import React, {FC, useEffect, useState} from "react";
import {Button, Form, Input, message} from "antd";
import {Link, useNavigate, useParams, useSearchParams,} from "react-router-dom";
// 导入正则规则
import {reg} from "../utils";

import api from "../api";

const AccountLogin: FC = () => {
    const [form] = Form.useForm();
    const [, forceUpdate] = useState({});
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    useEffect(() => {
        forceUpdate({});
    }, []);

    return (
        <Form form={form} name="horizontal_login" initialValues={{phone: searchParams.get("phone")}} layout="vertical"
              onFinish={(values) => {
                  delete values.confirmPassword;
                  // 登录
                  api.login(values).then((res) => {
                      if (res.code === 200) {
                          message.success("登录成功");
                          // 存储token
                          sessionStorage.setItem("token", res.token)
                          // 跳转到首页
                          navigate('/')
                      } else {
                          message.error(res.msg);
                      }
                  }).catch((err) => {
                      message.error(err.message);
                  })
              }}>
            <Form.Item label="手机号" name="phone"
                       rules={[
                           {required: true, message: '手机号是必填项'},
                           {pattern: reg.phone, message: '请输入正确的手机号'}
                       ]}>
                <Input type="tel" placeholder="请输入手机号"/>
            </Form.Item>
            <Form.Item label="密码" name="password"
                       rules={[
                           {required: true, message: '密码是必填项'},
                           {
                               pattern: reg.password,
                               message: '请输入6-16的密码包含数字、字母、字符中的两种'
                           }
                       ]}>
                <Input.Password type="password" placeholder="请输入密码"/>
            </Form.Item>
            <Form.Item>
                <div style={{display: "flex", justifyContent: "space-between"}}>
                    <Link to="/register">没有密码，去注册</Link>
                    <Link to="/forget">忘记密码，去重置</Link>
                </div>
            </Form.Item>
            <Form.Item>
                <Button block type="primary" htmlType="submit">登录</Button>
            </Form.Item>
            <Form.Item>
                <Button block htmlType="reset">重置</Button>
            </Form.Item>
        </Form>
    );
}

export default AccountLogin;